package com.example.controller;

import com.example.domain.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-09 10:13
 **/
// @WebServlet("/users")
public class UserController extends HttpServlet {
    UserService userService = new UserServiceImpl();

    public User login(String username, String password) {
        User user = userService.login(username, password);
        return user;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");
        if ("login".equals(method)) {
            String password = req.getParameter("password");
            String username = req.getParameter("loginName");
            User user = login(username, password);
            System.out.println(user);
            if (user == null) {
                //errorMsg
                req.setAttribute("errorMsg", "账户名或者密码错误");
                req.getRequestDispatcher("/html/login.jsp").forward(req, resp);
                // resp.sendRedirect(getServletContext().getContextPath() + "/html/login.jsp");
            } else {
                //怎么显示到页面上呢
                //sessionScope.userinfo.username
                HttpSession session = req.getSession();
                session.setAttribute("userinfo", user);
                req.getRequestDispatcher("/html/frame.html").forward(req, resp);
                // resp.sendRedirect(getServletContext().getContextPath() + "/html/frame.html");
            }

        }
    }
}
